package by.siarhei.java.tij.access.exercises.ex08;

/**
 * @author Siarhei Shchahratsou <s.siarhei@gmail.com>
 * @since 09.03.14
 */
public class ConnectionManager {
    public final static int POOL_SIZE = 4;
    private final Connection[] connectionPool = new Connection[POOL_SIZE];
    private int connectionRequest;

    public ConnectionManager() {
        for (int i = 0; i < connectionPool.length; i++) {
            connectionPool[i] = Connection.makeNewConnection();
        }
    }

    public Connection getConnection() {
        if (POOL_SIZE == connectionRequest) {
            return null;
        } else {
            return connectionPool[connectionRequest++];
        }
    }

    public static void main(String[] args) {
        ConnectionManager connectionManager = new ConnectionManager();

        for (int i = 0; i < ConnectionManager.POOL_SIZE + 1; i++) {
              System.out.println(connectionManager.getConnection());
        }
    }
}

class Connection {

    private static int count;
    private final int id = count++;

    private Connection() {
    }

    static Connection makeNewConnection() {
        return new Connection();
    }

    @Override
    public String toString() {
        return "Connection " + id;
    }
}
